<?php
class Server {
  public static function submit_obj($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    
    if (isset($req->id) && $req->id != 0) {
      if (isset($req->__nofile) && $req->__nofile == 1) {
        $attr = $req->__attr;
        if (file_exists($req->$attr)) {
          unlink($req->$attr);
        }
        unset($req->__nofile);
        unset($req->__attr);
        $req->$attr = '';
      }
      $orm->update('pb_page', $req);
    } else {
      $opts = new stdClass();
      $opts->cd = 't.sys_id = :v1';
      $opts->cdv = array(':v1' => $req->sys_id);
      $opts->sel = 't.order';
      $pages = $orm->get('pb_page', 't.order', 'DESC', 1, 1, $opts)->d;
      if (count($pages) > 0) {
        $req->order = $pages[0]->order + 1;
      }
      
      $orm->add('pb_page', $req);
      $req->id = $orm->last_id();
    }
    Server::__clear();
    $opts = new stdClass();
    $opts->cd = 't.sys_id = :v1';
    $opts->cdv = array(':v1' => SYS_ID);
    $req->__objs = $orm->get('pb_page', NULL, NULL, NULL, NULL, $opts)->d;
    echo json_encode($req);
  }
  
  public static function get_obj($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    
    $opts = new stdClass();
    $opts->cd = 't.id = :v1';
    $opts->cdv = array(':v1' => $req->id);
    $res = $orm->get('pb_page', NULL, NULL, NULL, NULL, $opts)->d;
    echo json_encode($res);
  }
  
  public static function __clear() {
    if (isset($_SESSION[SYS . 'index'])) {
      unset($_SESSION[SYS . 'index']);
    }
  }
  
  public static function upload_icon($orm, $sys, $inst, $is_iframe) {
    if (isset($_FILES['Filedata']) && is_uploaded_file($_FILES['Filedata']['tmp_name']) && $_FILES['Filedata']['error'] == 0) {
      //获得上传文件信息
      $upload_file = $_FILES['Filedata'];
      //获取文件扩展名
      $file_info = pathinfo($upload_file['name']);
      $file_ext = (isset($file_info['extension'])) ? $file_info['extension'] : '';
      
      $updir = UPLOAD_DIR_PLGN . $inst->__folder;
      if (!file_exists($updir)) {
        Utils::create($updir);
      }
        
      //获取客户端参数
      $id = Utils::get_param('id', 0);
      $file = Utils::get_param('file', '');
      $attr = Utils::get_param('attr', '');
      if (file_exists($file) && is_file($file)) {
        unlink($file);
      }
      
      //Add custom code here...
      $file_ext = strtolower((isset($file_info['extension'])) ? $file_info['extension'] : '');
      $res = new stdClass();
      $res->id = $id;
      $res->$attr = (($id == 0) ? TMP_DIR : $updir) . '/' . Utils::unique() . '.' . $file_ext;
      if (move_uploaded_file($upload_file['tmp_name'], $res->$attr)) {
        if ($id != 0) {
          $orm->update('pb_page', $res);
        }
        echo json_encode($res);
      }
    }
  }
}
?>